import { useState, useEffect, forwardRef, useImperativeHandle, useRef, useCallback, useMemo } from "react";
import {
	Button,
	DatePicker,
	Col,
	Row,
	Space,
	Popover,
	Tooltip,
	Image,
	Typography,
	Form,
	InputNumber,
	Modal,
	Select,
	message
} from "antd";
import { PrefixPlaceholder, Input, BatchSuffixInput } from "@/views/components/PrefixPlaceholder";
import { QuestionCircleOutlined } from "@ant-design/icons";
import { CommonModal } from "@/views/components/CommonModal";
import { getGoodsSkuPage } from "../../../service";
import { SearchSimpleTable } from "@/views/components/SearchTable/index";
import CommonZjfImg from "@/views/components/CommonZjfImg";
import { useTableConfig } from "@/views/components/SearchTable/hooks/useTableConfig";
import { NumText } from "@/pages/OrderModule/common/components/CommonText";
import {
	getArrayItem,
	SPU_STATUS,
	SPU_SYNC_STATUS,
	SPU_PRICE_TYPE,
	SPU_OTHER_ATTR,
	YES_NO_NUM_STATUS
} from "@/views/utils/constant";
const { Text } = Typography;
import moment from "moment";
import { cloneDeep, set } from "lodash";
import { submitMemberPriceApply } from "../../../service";
const { RangePicker } = DatePicker;
const dateFormat = "YYYY-MM-DD HH:mm:ss";

const ImageBox = ({ children }) => {
	return <div style={{ display: "flex", alignItems: "center", justifyContent: "center" }}>{children}</div>;
};

const GoodsListModal = forwardRef(
	(
		{
			rowKey = "id",
			visible,
			handleCancel,
			selectName,
			selectedIds: defaultSelectedIds,
			selectedSkuCodes: defaultSelectedSkuCodes,
			records,
			isExactMatch = 1,
			onSubmitSuccess,
			...args
		},
		ref
	) => {
		const [selectedIds] = useState(defaultSelectedIds || []);
		const [selectedSkuCodes] = useState(defaultSelectedSkuCodes);
		const [selectedRowKeys, setSelectedRowKeys] = useState([]);
		const [priceKeysObject, setPriceKeysObject] = useState({});
		const [errText, setErrText] = useState("");

		const [errRowKeys, setErrRowKeys] = useState([]);
		const [isView, setIsView] = useState(false);

		const higherErrorIds = useRef([]);

		const tableRequest = getGoodsSkuPage;
		let defaultId = 0;
		const formatZjfImg = ({ img, storeId, size = 48 }) => {
			//检测图片是否是完整路径，如果不是需要拼接
			if (!img) {
				return `https://imgniu.zhaojiafang.com/no-img${size}.jpg`;
			}
			if (/^(http|https)/.test(img)) {
				if (/zhaojiafang/.test(img)) {
					return size ? `${img}_${size}x${size}` : img;
				} else {
					return img;
				}
			} else {
				return size
					? `https://imgniu.zhaojiafang.com/store/goods/${storeId}/${img}_${size}x${size}`
					: `https://imgniu.zhaojiafang.com/store/goods/${storeId}/${img}`;
			}
		};
		const columns = useMemo(() => {
			return [
				{
					name: "序号",
					code: "index",
					render: (t, r, i) => i + 1,
					lock: true,
					width: 60
				},
				{
					name: "图片",
					code: "image",
					render: (value, record) => (
						<ImageBox>
							<Image height={32} src={value} />
						</ImageBox>
					)
				},
				{
					name: "系统款式编码",
					code: "spuCode",
					width: 160,
					// formItemProps: {
					// 	initialValue: records ? records.spuCode : ""
					// },
					search: {
						order: 1,
						content: () => <Input placeholder="系统款式编码" />
					}
				},
				{
					name: "系统商品编码",
					code: "skuCode",
					width: 160,
					// defaultValue={records ? records.skuCode : ""}
					search: { order: 2, content: () => <Input placeholder="系统商品编码" /> }
				},
				{
					name: "系统商品名称",
					code: "skuName",
					searchCode: "skuNameOrCode",
					width: 160,
					search: { order: 3, content: () => <Input placeholder="系统商品名称" /> }
				},
				{
					name: "系统商品简称",
					code: "skuAbbreviation",
					width: 160,
					search: { order: 4, content: () => <Input placeholder="系统商品简称" /> }
				},
				{
					name: "系统颜色规格",
					code: "colorSpecifications",
					search: { order: 5, content: () => <Input placeholder="系统颜色及规格" /> }
				},
				{
					hidden: true,
					name: "商品类型",
					code: "type",
					width: 160
					// search: {
					// 	order: 12,
					// 	content: () => (
					// 		<Select
					// 			allowClear
					// 			placeholder="商品类型"
					// 			options={[
					// 				{
					// 					label: "单商品",
					// 					value: 1
					// 				},
					// 				{
					// 					label: "组合",
					// 					value: 2
					// 				}
					// 			]}
					// 		></Select>
					// 	)
					// }
				},
				{
					name: "零售价（元）",
					render: value => value && <NumText as="s1" pre="¥" num={value} />,
					code: "retailPrice",
					search: {
						span: 3,
						order: 13,
						content: () => {
							const [isFocus, setIsFocus] = useState(false);
							const focusStyle = isFocus
								? {
										display: "flex",
										boxShadow: "rgba(1, 101, 213, 0.2) 0px 0px 0px 2px",
										borderRadius: "4px",
										backgroundColor: "#fff",
										"--color-bg-form-control": "#fff"
									}
								: { display: "flex" };
							return (
								<Input.Group compact style={focusStyle}>
									<Form.Item name="priceType" noStyle>
										<Select
											placeholder="选择价格"
											options={[
												{
													value: 1,
													label: "零售价"
												},
												{
													value: 2,
													label: "商城价"
												}
											]}
											style={{
												flex: 1,
												background: "transparent"
											}}
										/>
									</Form.Item>
									<Form.Item name="minPrice" style={{ textAlign: "center", flex: 1, marginBottom: 0 }}>
										<InputNumber
											onFocus={() => setIsFocus(true)}
											onBlur={() => setIsFocus(false)}
											min={0}
											placeholder="最小值"
											style={{
												textAlign: "center",
												flex: 1
											}}
											controls={false}
										/>
									</Form.Item>
									<Input
										style={{
											width: 30,
											borderLeft: 0,
											borderRight: 0,
											pointerEvents: "none"
										}}
										placeholder="-"
										disabled
									/>
									<Form.Item name="maxPrice" style={{ textAlign: "center", flex: 1, marginBottom: 0 }}>
										<InputNumber
											min={0}
											placeholder="最大值"
											style={{
												textAlign: "center",
												flex: 1
											}}
											controls={false}
										/>
									</Form.Item>
								</Input.Group>
							);
						}
					}
				},
				// {
				// 	hidden: true,
				// 	// name: "采购价（元）",
				// 	// code: "purchasePrice",
				// 	// render: value => value && <NumText as="s1" pre="¥" num={value} />,
				// 	search: {
				// 		order: 14,
				// 		span: 3,
				// 		group: [
				// 			{
				// 				span: 11,
				// 				code: "attributeType",
				// 				content: () => <Select placeholder="其他属性" options={SPU_OTHER_ATTR} className="width-full" />
				// 			},
				// 			{
				// 				span: 13,
				// 				code: "attribute",
				// 				content: () => <Input placeholder="" />
				// 			}
				// 		]
				// 	}
				// },
				{
					name: "商城价（元）",
					code: "mallPrice",
					render: value => value && <NumText as="s1" pre="¥" num={value} />
				},
				{
					name: "会员价（元）",
					code: "memberPrice",
					render: (text, record) => (
						<InputNumber
							value={priceKeysObject[record.id]}
							disabled={!selectedRowKeys.includes(record.id)}
							min={0.01}
							precision={2}
							onBlur={e => handleNumChange(e, record)}
						/>
					),
					width: 200
				},
				{
					hidden: true,
					// name: "创建时间",
					// code: "createTime",
					// width: 180,
					// render: text => (text ? <div>{moment(text).format("YYYY-MM-DD HH:mm:ss")}</div> : ""),
					search: {
						order: 180,
						span: 6,
						group: [
							{
								span: 5,
								code: "dateType",
								content: () => (
									<Select className="width-full" placeholder="选择日期" allowClear>
										<Option value={1}>修改日期</Option>
										<Option value={2}>创建日期</Option>
										{/* <Option value={3}>最后同步日期</Option> */}
									</Select>
								)
							},
							{
								keys: ["startTime", "endTime"],
								span: 19,
								code: "time",
								content: () => <RangePicker format={dateFormat} showTime />
							}
						]
					}
				},
				{
					hidden: true,
					render: text => (text ? <div>{moment(text).format("YYYY-MM-DD HH:mm:ss")}</div> : ""),
					search: { code: "supplierSpuCode", order: 7, content: () => <Input placeholder="供应商款式编码" /> }
				},
				{
					hidden: true,
					search: { code: "supplierSkuCode", order: 8, content: () => <Input placeholder="供应商商品编码" /> }
				},
				// {
				// 	hidden: true,
				// 	search: {
				// 		code: "matchOrNot",
				// 		order: 10,
				// 		content: () => <Select options={YES_NO_NUM_STATUS} placeholder="是否仅匹配供应商" />
				// 	}
				// },
				{
					hidden: true,
					search: {
						code: "isManyGoods",
						order: 11,
						content: () => <Select options={YES_NO_NUM_STATUS} placeholder="是否多个商品匹配" />
					}
				},
				{
					name: "商品匹配",
					code: "goodsSkuMatches",
					width: 200,
					render: (vals, record) => {
						const options = vals
							.filter(item => item.supplierSkuName)
							.map(item => {
								return {
									// label: `${item.supplierName}*${item.supplierSpuCode}*${item.supplierSkuName}*${item.supplierSkuCode}`,
									label: item.supplierName,
									value: item.id
								};
							});
						defaultId = vals.filter(item => item.supplierSkuName && item.isDefault)[0]?.id || vals[0]?.id;
						return (
							<Select
								onChange={e => {
									vals.forEach(val => {
										val.isDefault = val.id === e ? true : false;
									});
									// 把vals中id是23的放到第一位
									const newVals = [...vals];
									const index = newVals.findIndex(_item => _item.id == e);
									if (index > -1) {
										const temp = newVals[index];
										newVals[index] = newVals[0];
										newVals[0] = temp;
										record.goodsSkuMatches = newVals;
										record.supplierSkuImage = newVals[0].supplierSkuImage;
										record.supplierSkuName = newVals[0].supplierSkuName;
										record.supplierSkuSpecs = newVals[0].supplierSkuSpecs;
										record.mallPrice = newVals[0].supplierSkuPrice;
										record.supplierId = newVals[0].supplierId;
										record.supplierName = newVals[0].supplierName;
										record.supplierSkuId = newVals[0].supplierSkuId;
										record.supplierSpuCode = newVals[0].supplierSpuCode;
									}
									updateDataSource(pre => {
										const __pre = cloneDeep(pre);
										__pre.forEach(e => {
											if (e.id == record.id) {
												e.goodsSkuMatches = newVals;
											}
										});
										return __pre;
									});
								}}
								disabled={!selectedRowKeys.includes(record.id)}
								style={{ width: "100%" }}
								value={defaultId}
								placeholder="商品匹配"
								options={options}
							/>
						);
						// return (
						// 	<div>
						// 		{(record.goodsSkuMatches || []).map((item, i) => {
						// 			return (
						// 				<p key={i + item.id} style={{ lineHeight: "16px" }}>
						// 					{item.supplierName}*{item.supplierSpuCode}*{item.supplierSkuName}*{item.supplierSkuCode}
						// 					{item.isDefault && "（默认）"}
						// 				</p>
						// 			);
						// 		})}
						// 	</div>
						// );
					}
				},
				{
					name: "供应商商品图片",
					code: "supplierSkuImage",
					width: 130,
					render: (_, record) => {
						return (
							<ImageBox>
								<Image
									height={32}
									width={32}
									src={formatZjfImg({ img: record.supplierSkuImage, storeId: record.supplierId, size: 0 })}
								></Image>
							</ImageBox>
						);
					}
				},
				{
					hidden: true,
					name: "供应商名称",
					code: "supplierName",
					width: 160,
					search: { order: 6, content: () => <Input placeholder="供应商名称" /> }
				},
				{
					name: "供应商商品名称",
					code: "supplierSkuName",
					width: 130
				},
				{
					name: "供应商颜色规格",
					code: "supplierSkuSpecs"
				}
			];
		}, [selectedRowKeys]);

		const onOk = async () => {
			if (selectedAllPagesRows.current.length > 0) {
				setErrText("");
				// 判断selectedAllPagesRows.current 这个数组，里面是否所有的item都有了newPrice字段
				const nilErrKeys = selectedAllPagesRows.current.filter(item => !item.newPrice).map(item => item.skuCode);
				const higherErrKeys = selectedAllPagesRows.current
					.filter(item => item.newPrice > item.mallPrice)
					.map(item => item.skuCode);

				// 找出 selectedAllPagesRows.current 中，字段supplierSkuId的值 出现一次以上的数据
				const countMap = selectedAllPagesRows.current.reduce((acc, row) => {
					acc[row.supplierSkuId] = (acc[row.supplierSkuId] || 0) + 1;
					return acc;
				}, {});
				const sameSupplierSkuIdAndDiffPrice = [];
				Object.keys(countMap).forEach(key => {
					if (countMap[key] > 1) {
						const tmp1 = selectedAllPagesRows.current.filter(row => row.supplierSkuId == key);
						const priceTmp = tmp1.map(row => row.newPrice);
						new Set([...priceTmp]).size > 1 &&
							sameSupplierSkuIdAndDiffPrice.push(`【${tmp1.map(row => row.skuCode).join(",")}】`);
					}
				});
				if (!nilErrKeys.length && !higherErrKeys.length && !sameSupplierSkuIdAndDiffPrice.length) {
					setErrRowKeys([]);

					const res = await submitMemberPriceApply({
						memberList: selectedAllPagesRows.current.map(item => {
							return {
								...item,
								skuId: item.id
							};
						})
					});
					const errTips = [];
					higherErrorIds.current = [];
					if (res?.data?.alreadyExistsError?.length) {
						errTips.push("部分供应商商品已存在使用中/待审核的会员价，无需再次申请，已为您过滤");
					}
					if (res?.data?.higherError?.length) {
						errTips.push("部分商品会员价高于商品商城价，您可点击查看重新申请");
						higherErrorIds.current = res.data.higherError;
					}

					if (errTips.length) {
						Modal.info({
							title: "提示",
							content: <div>{errTips.join("，")}</div>,
							okText: higherErrorIds.current.length ? "查看" : "知道了",
							okButtonProps: {
								type: higherErrorIds.current.length ? "primary" : "link"
							},
							onOk() {
								if (higherErrorIds.current.length) {
									setErrRowKeys(higherErrorIds.current);
									RefTable.current.setTableSelect(higherErrorIds.current);
								} else {
									onCancel();
								}
							}
						});
					} else {
						onSubmitSuccess && onSubmitSuccess();
						onCancel();
					}
				} else {
					if (nilErrKeys.length > 0) {
						setErrRowKeys(nilErrKeys);
						setErrText("存在会员价为空的商品：" + nilErrKeys.join(","));
						message.error("存在会员价为空的商品");
						return;
					}
					if (higherErrKeys.length > 0) {
						setErrRowKeys(higherErrKeys);
						setErrText("存在会员价高于商品商城价的商品：" + higherErrKeys.join(","));
						Modal.info({
							title: "提示",
							content: "部分商品会员价高于商品商城价，您可点击查看重新申请",
							okText: "查看",
							okButtonProps: {
								type: "primary"
							}
						});
						return;
					}
					if (sameSupplierSkuIdAndDiffPrice.length > 0) {
						const strTemp = sameSupplierSkuIdAndDiffPrice.join(",").replace(/【|】/g, ",").split(",");
						setErrRowKeys(strTemp);
						setErrText("存在同供应商商品的系统商品会员价不一致，请确认：" + sameSupplierSkuIdAndDiffPrice.join(","));
						message.error("存在同供应商商品的系统商品会员价不一致，请确认");
						return;
					}
				}
			} else {
				message.error("先选择商品");
				return;
			}
		};

		const [formModal] = Form.useForm();
		const selectionChange = (__selectedRowKeys, __selectedRows) => {
			setSelectedRowKeys(__selectedRowKeys);
			setInputValueByRows(__selectedRows);
		};

		function setInputValueByRows(__selectedRows) {
			// const v = (__selectedRows || []).map(e => `${e.skuCode}*${e.num || 1}`).join(",");
			const v = (__selectedRows || []).map(e => `${e.skuCode}`).join(",");
			formModal.setFieldValue("inputValue", v);
		}

		const onCancel = () => {
			handleCancel();
			formModal.resetFields();
		};
		const tableKey = "__GoodsListModal__";
		const {
			RefTable,
			fetchList,
			selectedAllPagesRows,
			searchSimpleTableProps,
			dataSource,
			form,
			query,
			updateSearchQuery,
			updateDataSource
		} = useTableConfig({
			beforeReset() {
				setErrText("");
				setErrRowKeys([]);
			},
			tableKey,
			rowKey,
			keepSelected: true,
			columns,
			tableRequest,
			autoFetch: false,
			hasPagination: true,
			hasQuickSearch: false,
			hasToggleSearchForm: true,
			beforeQuerySearch: ({ API_DATA }) => {
				if (selectName == "update") {
					API_DATA.spuCode = records.spuCode;
				}
				// 是否为精准匹配1是0否
				if (isExactMatch) {
					API_DATA.isExactMatch = isExactMatch;
				}
				if (selectName == "search") {
					API_DATA.spuCode = records.spuCode;
					API_DATA.skuCode = records.skuCode;
				}
				return {
					...API_DATA
					// type: 1
				};
			},
			resetSourceData: false,
			hasColsSetting: false,
			selectionChange
		});

		useEffect(() => {
			if (selectedSkuCodes.length) {
				console.log("%celelee test:", "background:#000;color:#fff", 99999, selectedIds, selectedSkuCodes);
				setTimeout(() => {
					form.setFieldValue("skuCode", selectedSkuCodes.join(","));
					fetchList({ skuCode: selectedSkuCodes.join(",") }).then(res => {
						setTimeout(() => {
							RefTable.current.RefSearchTable.setTableSelect(selectedIds);
						}, 200);
					});
				}, 300);
			}
		}, [selectedIds, selectedSkuCodes]);

		useEffect(() => {
			if (selectedSkuCodes.length) {
				return;
			}
			if (selectName == "search") {
				updateSearchQuery({ spuCode: records.spuCode, skuCode: records.skuCode });
				form.setFieldValue("skuCode", records.skuCode);
				form.setFieldValue("spuCode", records.spuCode);
				fetchList({ spuCode: records.spuCode, skuCode: records.skuCode });
			} else if (selectName == "update") {
				updateSearchQuery({ spuCode: records.spuCode });
				fetchList({ spuCode: records.spuCode });
				form.setFieldValue("spuCode", records.spuCode);
			} else {
				fetchList();
			}
		}, []);
		const handleNumChange = (e, record, index) => {
			const reg = /^[1-9]\d*$/;
			const val = e.target.value;
			const [integerPart] = val.split(".");

			if (integerPart.length > 10) {
				message.error("限制10个整数位");
				return;
			}

			if (val) {
				setErrRowKeys(pre => pre.filter(e => e != record.id));
				setPriceKeysObject(pre => ({ ...pre, [record.id]: Number(val) }));
				selectedAllPagesRows.current.find(e => e.id == record.id).newPrice = Number(val);
				// updateDataSource(pre => {
				// 	const arr = cloneDeep(pre);
				// 	let list = [];
				// 	arr.forEach((element, i) => {
				// 		if (element.id == record.id) {
				// 			element.num = val;
				// 			selectedAllPagesRows.current.forEach(j => {
				// 				if (j.id == element.id) {
				// 					j.num = element.num;
				// 					list.push(element);
				// 				}
				// 			});
				// 		}
				// 		return element;
				// 	});
				// 	const v = (selectedAllPagesRows.current || []).map(e => `${e.skuCode}*${e.num || 1}`).join(",");
				// 	formModal.setFieldValue("inputValue", v);
				// 	return arr;
				// });
			} else {
				// message.error("需要输入正整数");
			}
		};
		const commonPressEnter = async inputValue => {
			//RefTable?.current?.clearTableSelected();

			//去空格
			const str = String(inputValue).replace(/\s+/g, "");
			const arr = str.split(/[,，]/).map(text => {
				const arr1 = text.split("*");
				return {
					skuCode: arr1[0] || "", //默认为空
					num: arr1[1] || 1 //默认为1
				};
			});
			//更新数据
			updateDataSource(pre => {
				const __pre = cloneDeep(pre);
				const ids = [];
				__pre.map((row, i) => {
					// 根据 skuCode查找
					const f = arr.find(e => e.skuCode == row.skuCode);
					if (f && f.skuCode) {
						//更新数量
						row.num = f.num;
						//收集回显id
						ids.push(row[rowKey]);
					}

					return cloneDeep(row);
				});
				//需要在updateDataSource更新后，执行回显方式
				setTimeout(() => {
					RefTable?.current?.setTableSelect?.(ids);
					if (isView) formModal.setFieldValue("inputValue", inputValue); // 查看模式下，无checkbox，不会执行setTableSelect、所以需要手动回显inputValue
				}, 10);
				return __pre;
			});
		};

		useImperativeHandle(ref, () => ({
			// 暴露给父组件的方法
			RefTable: RefTable.current,
			name: "GoodsListModal",
			...(RefTable.current || {}),
			commonPressEnter,
			handleFocusChange: commonPressEnter
		}));

		const getSearchFormVal = useCallback(() => {
			return {
				search: { skuCode: formModal.getFieldValue("inputValue") },
				allPagesSelected: selectedAllPagesRows.current
			};
		}, []);

		return (
			<CommonModal
				{...args}
				className="views-table-dialog"
				title={{
					title: (
						<>
							选择商品（申请会员价仅支持精准匹配的商品）
							<Tooltip title="同供应商商品匹配的多个系统商品，提交申请会一同提交且会员价一致">
								<QuestionCircleOutlined />
							</Tooltip>
						</>
					)
				}}
				visible={true}
				width="86vw"
				height="75vh"
				onOk={onOk}
				onCancel={handleCancel}
				footer={
					<div>
						{!!errText && <div style={{ color: "#F03D29", fontSize: "12px", textAlign: "left" }}>{errText}</div>}
						<div style={{ display: "flex", justifyContent: "space-between" }}>
							<Row style={{ width: "70vw" }}>
								<Col span={24}>
									<Form form={formModal}>
										<Form.Item name="inputValue" label="">
											<Input readOnly={isView} onPressEnter={e => commonPressEnter(e.target.value)} />
										</Form.Item>
									</Form>
								</Col>
							</Row>
							<Row>
								<Col>
									<Space>
										<Button size="middle" onClick={onCancel}>
											取消
										</Button>
										{!isView && (
											<Button size="middle" type="primary" onClick={onOk}>
												确定
											</Button>
										)}
									</Space>
								</Col>
							</Row>
						</div>
					</div>
				}
				destroyOnClose
			>
				<div className="views-container member-price-modal-wrapper">
					<SearchSimpleTable
					  maxCol={5}
						tableRef={RefTable}
						getRowProps={(record, rowIndex) => {
							return {
								style: errRowKeys.includes(record.skuCode)
									? {
											"--hover-bgcolor": "#F03D29",
											"--bgcolor": "#F03D29",
											zoom: 0.8
										}
									: {
											"--bgcolor": "#fff",
											zoom: 0.8
										}
							};
						}}
						type={"checkbox"}
						key={tableKey}
						mounted={false}
						{...searchSimpleTableProps}
						showMoreAction
						getSearchFormVal={getSearchFormVal}
					/>
				</div>
			</CommonModal>
		);
	}
);

export default GoodsListModal;
